package org.at.diary.user;

import org.at.nhatky1.R;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ChangePassword extends Activity {
	
	EditText edtOldPassword;
	EditText edtNewPassword;
	EditText edtReNewPassword;
	Button btnOk;
	Button btnCancel;
	
	String txtOldPasswordFromType;
	String txtOldPasswordFromDatabase;
	String txtNewPassword;
	String txtReNewPassword;
	
	UserDatabaseAdapter userDbHelper;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.change_password);
		userDbHelper = new UserDatabaseAdapter(ChangePassword.this);
		userDbHelper.open();
		
		Cursor c = userDbHelper.fetchNote(1);
		startManagingCursor(c);
		
		txtOldPasswordFromDatabase = c.getString(c.getColumnIndexOrThrow(UserDatabaseAdapter.KEY_PASSWORD));
		
		edtOldPassword = (EditText) findViewById(R.id.edt_old_password);
		edtNewPassword = (EditText) findViewById(R.id.edt_new_password);
		edtReNewPassword = (EditText) findViewById(R.id.edt_renew_password);
		
		btnOk = (Button) findViewById(R.id.btnOk);
		btnCancel = (Button) findViewById(R.id.btnCancel);
		
		btnOk.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				txtOldPasswordFromType = edtOldPassword.getText().toString();
				txtNewPassword = edtNewPassword.getText().toString();
				txtReNewPassword = edtReNewPassword.getText().toString();
				
				if (txtNewPassword.equals("") || txtReNewPassword.equals("")){
					Toast.makeText(ChangePassword.this, "Vui lòng nhập đủ thông tin", Toast.LENGTH_SHORT).show();
				} else{
					if (txtOldPasswordFromType.equals(txtOldPasswordFromDatabase)){
						if(!txtNewPassword.equals(txtReNewPassword)){
							Toast.makeText(ChangePassword.this, "Hai mật khẩu bạn nhập không giống nhau", Toast.LENGTH_LONG).show();
						}
						userDbHelper.changePasswordUser(1, txtNewPassword);
						Toast.makeText(ChangePassword.this, "Đổi mật khẩu thành công. Vui lòng đăng nhập lại.", Toast.LENGTH_LONG).show();
						Intent i = getBaseContext().getPackageManager()
					             .getLaunchIntentForPackage( getBaseContext().getPackageName());
						i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(i);
						
					}
					else {
						Toast.makeText(ChangePassword.this, "Mâòt khâÒu cuÞ chýa ðuìng. Vui loÌng nhâòp laòi.", Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
		
		btnCancel.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		
	}
}
